import React, { useEffect, useState, useRef } from "react";
import Plotly from "plotly.js-dist-min";
import zhCN from "./zh-CN.json";
import { useTranslation } from "react-i18next";
import "./index.less";
import { isValidDate } from "@/utils/index";
import { Table } from "antd";
// import FullScreenPlotlyBox from '@/components/FullScreenPlotlyBox'

interface IProps {
  chatInfo: {
    msgId: string;
    dataId: string;
  };
  rsourceData: any;
  language: AppLanguageType;
  onRender?: (isForce?: boolean) => void;
}

const defaultConfig: Partial<Plotly.Config> = {
  displaylogo: false,
};

const ChatPlotly: React.FC<IProps> = ({
  chatInfo,
  rsourceData,
  language,
  onRender,
}) => {
  const { t } = useTranslation();
  const rootFontSize = parseFloat(
    getComputedStyle(document.documentElement).fontSize
  );

  const calculateWidth = () => {
    // 获取视口宽度（vw）
    const viewportWidth = window.innerWidth;

    // 获取根元素的字体大小（rem），通常是 16px

    // 计算 100vw 和 5rem 的值
    const hundredVw = viewportWidth; // 100vw 的值
    const fiveRem = 5 * rootFontSize; // 5rem 的值

    // 计算 100vw - 5rem
    const result = hundredVw - fiveRem;

    return result; // 返回计算结果
  };

  const idStr = `chat-plotly-component-${chatInfo.msgId}-${chatInfo.dataId}`;
  const plotlyRef = useRef<HTMLDivElement>(null);
  const isRenderRef = useRef<boolean>(false);
  const [reactInfo, setReactInfo] = useState<DOMRect | null>(null);
  const [tableData, setTableData] = useState<any[]>([]);
  let title = rsourceData?.layout?.title ?? {};
  let legend = rsourceData?.layout?.legend ?? {};
  let xaxis = rsourceData?.layout?.xaxis ?? {};
  let yaxis = rsourceData?.layout?.yaxis ?? {};
  let data = rsourceData?.data?.map((item) => {
    let { x, y } = item;
    return {
      ...item,
      y: x,
      x: y,
      // orientation: 'v' // 垂直方向
    };
  });
  // ! 移动端额外处理
  const mobileLayout = {
    ...rsourceData?.layout,
    polar: {
      angularaxis: {
        rotation: 90, // 旋转 90 度
      },
    },
    title: {
      ...title,
      font: {
        size: 12, // 设置标题字体大小为 12
      },
    },
    legend: {
      ...legend,
      orientation: "h", // 水平布局
      yanchor: "bottom", // 图例的垂直锚点
      xanchor: "center", // 图例的水平锚点
      font: {
        size: 10, // 设置字体大小
      },
    },
    autosize: true,
    height: 300,
    width: calculateWidth(),
    margin: {
      // "t": 100,
    },
    xaxis: yaxis,
    yaxis: xaxis,
  };

  const handleSelected = (eventData: any) => {
    if (eventData && eventData.range && eventData.range.x) {
      const rangeXArr = eventData.range.x;
      const originDataX = rsourceData.data[0].x;
      const originDataY = rsourceData.data[0].y;
      let startIndex: number = -1;
      let endIndex: number = -1;
      originDataX.forEach((item: any, index: number) => {
        if (isValidDate(rangeXArr[0])) {
          if (new Date(item).valueOf() >= new Date(rangeXArr[0]).valueOf()) {
            if (startIndex === -1) {
              startIndex = index;
            } else if (index < startIndex) {
              startIndex = index;
            }
          }
        } else {
          if (rangeXArr[0] === item) {
            startIndex = index;
          }
        }
        if (isValidDate(rangeXArr[1])) {
          if (new Date(item).valueOf() <= new Date(rangeXArr[1]).valueOf()) {
            if (endIndex === -1) {
              endIndex = index;
            } else if (index > endIndex) {
              endIndex = index;
            }
          }
        } else {
          if (rangeXArr[0] === item) {
            endIndex = index;
          }
        }
      });
      const tableArr: any[] = [];
      if (startIndex !== -1 && endIndex !== -1 && startIndex <= endIndex) {
        originDataX.forEach((item: any, index: number) => {
          if (index <= endIndex && index >= startIndex) {
            const obj: any = {};
            obj.x = item;
            obj.y = originDataY[index];
            tableArr.push(obj);
          }
        });
      }
      setTableData(tableArr);
    }
  };
  const renderPloty = () => {
    if (rsourceData && plotlyRef.current) {
      Plotly.purge(plotlyRef.current);
      Plotly.react(
        plotlyRef.current,
        data,
        {
          ...mobileLayout,
        },
        {
          locale: language,
          locales: {
            "zh-CN": zhCN,
          },
          ...defaultConfig,
          ...(rsourceData.config || {}),
          // displayModeBar: false, // ! 隐藏工具栏
        }
      );
      isRenderRef.current = true;
      const info = plotlyRef.current.getBoundingClientRect();
      setReactInfo(info);
      (plotlyRef.current as any).on("plotly_selected", handleSelected);
    }
  };
  const renderFullScreenPloty = () => {
    const fullLayout = {
      ...rsourceData?.layout,
      title: {
        ...title,
        font: {
          size: 12, // 设置标题字体大小为 12
        },
      },
      legend: {
        ...legend,
        orientation: "h", // 水平布局
        yanchor: "bottom", // 图例的垂直锚点
        xanchor: "center", // 图例的水平锚点
        font: {
          size: 10, // 设置字体大小
        },
      },
      autosize: true,
      // height: window.innerWidth - rootFontSize * 2,
      // width: window.innerHeight,
      height: window.innerHeight,
      width: window.innerWidth - rootFontSize * 2,
      margin: {
        // "t": 100,
      },
      xaxis: yaxis,
      yaxis: xaxis,
    };

    if (rsourceData && plotlyRef.current) {
      Plotly.purge(plotlyRef.current);
      Plotly.react(
        plotlyRef.current,
        data,
        {
          ...fullLayout,
        },
        {
          locale: language,
          locales: {
            "zh-CN": zhCN,
          },
          ...defaultConfig,
          ...(rsourceData.config || {}),
          // displayModeBar: false, // ! 隐藏工具栏
        }
      );
      isRenderRef.current = true;
      const info = plotlyRef.current.getBoundingClientRect();
      setReactInfo(info);
      (plotlyRef.current as any).on("plotly_selected", handleSelected);
    }
    resize();
  };

  const purgePloty = () => {
    if (plotlyRef.current) {
      Plotly.purge(plotlyRef.current);
    }
  };
  const resize = () => {
    Plotly.Plots.resize(idStr);
    Plotly.redraw(idStr);
  };
  useEffect(() => {
    renderPloty();
    return () => {
      purgePloty();
    };
  }, [rsourceData]);
  useEffect(() => {
    const handleIntersection = (entries: any) => {
      entries.forEach((entry: any) => {
        if (isRenderRef.current) {
          if (entry.isIntersecting) {
            renderPloty();
          } else if (!entry.isIntersecting) {
            // ! 这边去掉销毁防止抖动 或者 用其他方法?
            // purgePloty()
          }
        }
      });
    };
    const observer = new IntersectionObserver(handleIntersection, {
      threshold: 0.1,
    });
    if (plotlyRef.current) {
      observer.observe(plotlyRef.current);
    }
    return () => {
      if (plotlyRef.current) {
        observer.unobserve(plotlyRef.current);
      }
    };
  }, []);
  return (
    <>
      <div
      // resize={resize}
      // resize={renderPloty}
      // fullResize={renderFullScreenPloty}
      // unFullResize={renderPloty}
      >
        <div
          id={idStr}
          style={{
            // height: reactInfo ? reactInfo.height : 'auto'
            height: "auto",
          }}
          ref={plotlyRef}
          className={`chat-plotly-component`}
        ></div>
      </div>

      {tableData.length > 0 && (
        <div className="chat-plotly-table">
          <div className="chat-plotly-table-title">
            {t("chat.selectedDataPoints")}
          </div>
          <Table
            columns={[
              {
                dataIndex: "x",
                key: "x",
                title: t("chat.tag"),
              },
              {
                dataIndex: "y",
                key: "y",
                title: t("chat.value"),
              },
            ]}
            dataSource={tableData}
          ></Table>
        </div>
      )}
    </>
  );
};

export default ChatPlotly;
